import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import Layout from '@/module-dashboard/pages/layout'
import { getToken } from '@/utils/auth'

// 定义
const _import = require('./import_' + process.env.NODE_ENV) // 懒加载 导包
const whiteList = ['/login', '/authredirect'] // 白名单 无需跳转

// 配置
Vue.use(Router)
NProgress.configure({ showSpinner: false }) // NProgress Configuration

// 静态页面
export const constantRouterMap = [
   {
      path: '/login',
      component: _import('dashboard/pages/login'),
      hidden: true
   },
   {
      path: '/authredirect',
      component: _import('dashboard/pages/authredirect'),
      hidden: true
   },
   { path: '/404', component: _import('dashboard/pages/404'), hidden: true },
   { path: '/401', component: _import('dashboard/pages/401'), hidden: true },
   {
      path: '',
      component: Layout,
      redirect: 'dashboard',
      children: [
         {
            path: 'dashboard',
            component: _import('dashboard/pages/dashboard'),
            name: 'dashboard',
            meta: { title: '面板', icon: 'dashboard', noCache: true }
         }
      ]
   }
]

/**
 * 配置路由
 **/
const router = new Router({
   mode: 'history', // require service support
   scrollBehavior: () => ({ y: 0 }),
   routes: constantRouterMap
})

router.beforeEach(async (to, from, next) => {
   NProgress.start() // start progress bar
   if (getToken()) {
      // determine if there has token
      /* has token */
      if (to.path === '/login') {
         next({ path: '/' })
         NProgress.done() // if current page is dashboard will not triggerafterEach hook, so manually handle it
         NProgress.done() // if current page is dashboard will not trigger afterEach hook, so manually handle it
      } else {
         if (store.getters.roles.length === 0) {
            // 判断当前用户是否已拉取完user_info信息
            store
               .dispatch('GetUserInfo')
               .then(res => {
                  // 拉取user_info
                  const roles = res.data.roles // note: roles must be a array! such as: ['editor','develop']
                  // console.log(res)

                  store.dispatch('GenerateRoutes', { roles }).then(() => {
                     //   console.log(store.getters.permission_routers)
                     //   console.log(store.getters.addRouters)
                     // 根据roles权限生成可访问的路由表
                     router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
                     next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
                  })
               })
               .catch(() => {
                  store.dispatch('FedLogOut').then(() => {
                     Message.error('验证失败, 请重新登录')
                     next({ path: '/login' })
                  })
               })
            // const res = await store.dispatch('GetUserInfo')
            // console.log(res.roles)
            // const newRoutes = await store.dispatch('GenerateRoutes', res.roles.menus)
            // router.addRoute([...newRoutes], { path: '*', redirect: '/404', hidden: true })
            // next(to.path)
         } else {
            next()
         }
      }
   } else {
      /* has no token */
      if (whiteList.indexOf(to.path) !== -1) {
         // 在免登录白名单，直接进入
         next()
      } else {
         next('/login') // 否则全部重定向到登录页
         NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
      }
   }
})

router.afterEach(() => {
   NProgress.done() // finish progress bar
})

/**
 * 导出 基础路由
 **/
export default router

/**
 * 导出 业务路由
 **/
export const asyncRouterMap = [{ path: '*', redirect: '/404', hidden: true }]
